# -*- coding: utf-8 -*-
__author__ = 'lztkdr'
__date__ = '2020/12/4 9:57'

import logging
from logging.handlers import TimedRotatingFileHandler


class MyLog(object):
	def __init__(self, logger_name, writefile=True):
		# 定义handler的输出格式
		formatter = logging.Formatter('%(asctime)s %(levelname)s %(pathname)s(%(lineno)d) %(message)s')
		# 创建一个logger
		self._logger = logging.getLogger(logger_name)
		# 创建一个handler，用于输出到控制台
		console_Handler = logging.StreamHandler()
		console_Handler.setLevel(logging.DEBUG)
		console_Handler.setFormatter(formatter)
		# 给logger添加handler
		self._logger.addHandler(console_Handler)

		# 创建一个handler，用于写入日志文件
		if writefile:
			logfilename = logger_name + ".log"
			# 写入文件
			# log_file_handler = logging.FileHandler(logfilename)
			"""
			filename：日志文件名的prefix；		
			when：是一个字符串，用于描述滚动周期的基本单位，字符串的值及意义如下： 
			“S”: Seconds 
			“M”: Minutes 
			“H”: Hours 
			“D”: Days 
			“W”: Week day (0=Monday) 
			“midnight”: Roll over at midnight
			interval: 滚动周期，单位有when指定，比如：when=’D’,interval=1，表示每天产生一个日志文件
			backupCount: 表示日志文件的保留个数
			"""
			# 滚动写入文件
			log_file_handler = TimedRotatingFileHandler(filename=logfilename, when="D", interval=1, backupCount=30)
			# 默认 warn 才会写入文件
			log_file_handler.setLevel(logging.WARN)
			log_file_handler.setFormatter(formatter)
			self._logger.addHandler(log_file_handler)

	@property
	def logger(self):
		return self._logger


def test():
	logger = MyLog("test").logger
	logger.debug(u"111")
	logger.info(u"222")
	logger.warning(u"333")
	logger.error(u"444")
	logger.critical(u"555")


if __name__ == '__main__':
	test()
